package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.InsuranceConditionVO;
import com.itheima.sfbx.insurance.mapper.InsuranceConditionMapper;
import com.itheima.sfbx.insurance.pojo.InsuranceCondition;
import com.itheima.sfbx.insurance.service.IInsuranceConditionService;
import com.itheima.sfbx.insurance.service.IInsuranceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description：保险筛选项服务实现类
 */
@Slf4j
@Service
public class InsuranceConditionServiceImpl extends ServiceImpl<InsuranceConditionMapper, InsuranceCondition> implements IInsuranceConditionService {

    @Autowired
    private IInsuranceService insuranceService;


    @Override
    @Transactional
    public Boolean save(List<InsuranceConditionVO> insuranceConditionListVOs) {
        List<InsuranceCondition> list = BeanConv.toBeanList(insuranceConditionListVOs, InsuranceCondition.class);
        this.saveBatch(list);
        return true;
    }

    @Override
    @Transactional
    public Boolean update(List<InsuranceConditionVO> insuranceConditionVOs) {
        //根据保险id查询保险筛选项
        String insuranceId = insuranceConditionVOs.get(0).getInsuranceId();
        List<InsuranceCondition> list = this.lambdaQuery()
                .eq(InsuranceCondition::getInsuranceId, insuranceId)
                .list();
        //删除原保险筛选项
        if(CollUtil.isNotEmpty(list)){
            List<Long> list1 = list.stream().map(InsuranceCondition::getId)
                    .collect(Collectors.toList());
            this.removeByIds(list1);
        }
        //最后保存
        return this.save(insuranceConditionVOs);
    }


    @Override
    public List<InsuranceConditionVO> findList(InsuranceConditionVO vo) {
        List<InsuranceCondition> list = this.lambdaQuery()
                .eq(StrUtil.isNotBlank(vo.getConditionKey()), InsuranceCondition::getConditionKey, vo.getConditionKey())
                .eq(StrUtil.isNotBlank(vo.getDataState()), InsuranceCondition::getDataState, vo.getDataState())
                .eq(StrUtil.isNotBlank(vo.getInsuranceId()), InsuranceCondition::getInsuranceId, vo.getInsuranceId())
                .like(StrUtil.isNotBlank(vo.getConditionKeyName()), InsuranceCondition::getConditionKeyName, vo.getConditionKeyName())
                .list();
        List<InsuranceConditionVO> voList = BeanConv.toBeanList(list, InsuranceConditionVO.class);
        return voList;
    }

}
